import React, {Component} from 'react';
import {FlatList, View} from 'react-native';
import {globalStore} from "../../libs/ShareStore";
import {listViewStyle} from "./style/listViewStyle";
import FriendListData from "../../model/item/FriendListData";
import FriendListItem from "./item/FriendListItem";
import {FriendListStore} from "../../model/store/FriendListStore";


type FriendListStateType = {
    items:Array<FriendListData>,
    refreshing:boolean,
}

export default class FriendListView extends Component<any, FriendListStateType> {
    constructor(props) {
        super(props);

        this.state = {
            items:new Array<FriendListData>(),
            refreshing: false
        };
        globalStore.addFriendListener(this.onFriendUpdate.bind(this));
    }

    componentDidMount(): void {
        this.onFriendUpdate(globalStore.friendList);
    }


    onFriendUpdate(sessions:Array<FriendListStore>):void{
        this.setState( {
            items:sessions.map((v)=>{
                const data =  new FriendListData();
                data.id = v.auid;
                data.avatar = v.avatar;
                data.name = v.name;
                data.body = '';
                data.online = v.online;
                data.sign = v.sign;

                return data;
            }),
            refreshing: !this.state.refreshing
        });
    }

    render() {
        return (
            <View style = {listViewStyle.container}>
                <View style={listViewStyle.list}>
                    <FlatList
                        extraData = {this.state.refreshing}
                        data = {this.state.items}
                        renderItem = {({item})=><FriendListItem data={item} avatar={item.avatar}  body={item.body} name={item.name}  unread={item.unread}/>}
                    />
                </View>
            </View>
        );
    }
}

